const cancelBookingDao = require('../database/CancelBookingDao');
const bookingOrderDao = require('../database/BookingOrderDao');
const meetingRoomDao = require('../database/MeetingRoomDao');
const authMiddleware = require('../middleware/AuthMiddleWare');
const { success, fail } = require('../utils/response');

const onlineUsers = require('../utils/onlineUsers').getOnlineUsers();
const { getIo } = require('../socket');

const router = require('express').Router();

// 申请取消预订
router.post('/:orderId', authMiddleware.isAuthenticated, async (req, res) => {
  try {
    const orderId = req.params.orderId;
    const order = await bookingOrderDao.getOrderById(orderId);

    if (!order) {
      return res.status(404).json(fail(4001, '订单不存在'));
    }

    if (order.customer_id !== req.user.userId) {
      return res.status(403).json(fail(4001, '无权操作此订单'));
    }

    if (order.order_status !== '预定') {
      return res.status(400).json(fail(4001, '订单状态不可取消'));
    }

    // 计算退款比例
    const currentTime = new Date();
    const startTime = new Date(order.start_time);
    const timeDiff = startTime - currentTime;
    const hoursBefore = timeDiff / (1000 * 60 * 60);
    let refundRate = 0;

    if (hoursBefore >= 24) {
      refundRate = 0.75; // 提前24小时以上，退75%
    } else if (hoursBefore >= 12) {
      refundRate = 0.5;  // 提前12-24小时，退50%
    } else {
      refundRate = 0.25; // 提前12小时内，退25%
    }

    // 创建取消请求（初始状态为"待审核"）
    const cancelId = await cancelBookingDao.createCancelRequest({
      orderId,
      cancelTime: currentTime,
      refundRate,
      staffId: null,
      auditStatus: '待审核'
    });

    const io = getIo();
    const socketId = onlineUsers[req.user.userId];

    if (socketId) {
      io.to(socketId).emit('server:cancel-request-submitted', {
        cancelId,
        message: '取消申请已提交，请等待审核'
      });
    }

    res.status(201).json(success({ message: '取消申请已提交，请等待审核', cancelId }));

  } catch (error) {
    console.error('提交取消申请失败:', error);
    res.status(500).json(fail(5000, '提交取消申请失败'));
  }
});

// 获取所有未审核的取消请求（员工权限）
router.get('/unaudited', authMiddleware.isEmployee, async (req, res) => {
  try {
    const requests = await cancelBookingDao.getUnauditedCancelRequests();
    res.json(success(requests));
  } catch (error) {
    console.error('获取未审核取消请求失败:', error);
    res.status(500).json(fail(5000, '获取未审核取消请求失败'));
  }
});

// 获取所有未审核的取消请求（员工权限）
router.get('/unaudited', authMiddleware.isEmployee, async (req, res) => {
  try {
    const requests = await cancelBookingDao.getUnauditedCancelRequests();
    res.json(success(requests));
  } catch (error) {
    console.error('获取未审核取消请求失败:', error);
    res.status(500).json(fail(5000, '获取未审核取消请求失败'));
  }
});

// 员工审核取消请求
router.put('/:orderId/approve', authMiddleware.isEmployee, async (req, res) => {
  try {
    const orderId = req.params.orderId;
    const { auditStatus } = req.body;
    const staffId = req.user.userId;

    // 获取取消请求信息
    const [rows] = await cancelBookingDao.getCancelRequestsByOrderId(orderId);
    if (rows.length === 0) {
      return res.status(404).json(fail(4001, '取消申请不存在'));
    }

    const cancelRequest = rows;
    const cancelId = cancelRequest.id;

    // 更新取消请求状态
    const updateSuccess = await cancelBookingDao.updateCancelRequestWithStaff(cancelId, auditStatus, staffId);

    if (!updateSuccess) {
      return res.status(404).json(fail(4001, '取消申请不存在'));
    }

    let message = '取消申请审核完成';

    // 如果审核通过，则更新订单状态和会议室状态
    if (auditStatus === '已通过') {
      // 更新订单状态为“已取消”
      await bookingOrderDao.updateOrderStatus(orderId, '已取消');

      // 获取订单以获取会议室ID
      const order = await bookingOrderDao.getOrderById(orderId);
      const roomId = order.room_id;

      // 更新会议室状态为“空闲”
      await meetingRoomDao.updateRoomStatus(roomId, '空闲');

      // WebSocket 推送消息给用户
      const io = getIo();
      const socketId = onlineUsers[order.customer_id];

      if (socketId) {
        io.to(socketId).emit('server:cancel-request-approved', {
          orderId,
          message: '您的取消申请已审核通过'
        });
      }

      message = '取消申请已审核通过，订单已取消，会议室已释放';
    }

    res.json(success({ message }));

  } catch (error) {
    console.error('审核取消申请失败:', error);
    res.status(500).json(fail(5000, '审核取消申请失败'));
  }
});

module.exports = router;